
import React, { useState, useEffect, useRef, } from 'react';
import { Form, Input, Button, Modal, message } from 'antd';
import classNames from 'classnames';
import axios from 'axios'
import { useTranslation } from 'react-i18next';
import { BASE_URL } from '../utils/request';

const Login = ({ show, onEvent }) => {
  const { t } = useTranslation()

  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const [count, setCount] = useState(60);
  //表单类型
  const [formType, setFormType] = useState('login')
  const [isSendEmail, setIsSendEmail] = useState(false)

  // 找回密码
  const [findFormData, setFindFormData] = useState({
    username: '',
    code: '',
    password: '',
    passwordConfirm: ''
  })
  const emailRef = useRef(null)
  const forgetSubmit = async (e) => {
    const res = await axios({
      url: BASE_URL + 'resetPassword',
      method: 'post',   // 默认值
      data: e
    })
    if (res.data.code === 200) {
      messageApi.open({
        type: 'success',
        content: res.data.msg,
        duration: 3,
      });
      form.resetFields(); // 重置表单
      setFormType('login')
    } else {
      messageApi.open({
        type: 'error',
        content: res.data.msg,
        duration: 3,
      });
    }
  };
  //登录
  const [loginFormData, setLoginFormData] = useState({
    username: '',
    password: ''
  })
  const loginSubmit = async (e) => {
    const res = await axios({
      url: BASE_URL + 'front/login',
      method: 'post',   // 默认值
      data: e
    })
    if (res.data.code === 200) {
      messageApi.open({
        type: 'success',
        content: `${t('登录成功')}`,
        duration: 3,
      });
      const result = await axios({
        url: BASE_URL + 'getInfo',
        headers: {
          authorization: res.data.token,
        },
        method: 'get'   // 默认值
      })
      localStorage.setItem('userInfo', JSON.stringify(result.data.user))
      localStorage.setItem('token', res.data.token)
      close()
      window.location.reload()
    } else {
      messageApi.open({
        type: 'error',
        content: res.data.msg,
        duration: 3,
      });
    }
  }
  //注册
  const [registerFormData, setRegisterFormData] = useState({
    nickName: '',
    username: '',
    code: '',
    password: '',
    inviteCode: null, //邀请码
  })
  const registerSubmit = async (e) => {
    delete e.confirm
    const res = await axios({
      url: BASE_URL + 'front/register',
      method: 'post',   // 默认值
      data: e
    })
    if (res.data.code === 200) {
      messageApi.open({
        type: 'success',
        content: `${t('注册成功')}`,
        duration: 3,
      });
      form.resetFields(); // 重置表单
      setFormType('login')
    } else {
      messageApi.open({
        type: 'error',
        content: res.data.msg,
        duration: 3,
      });
    }
  }
  const close = () => {
    form.resetFields(); // 重置表单
    setFormType('login')
    onEvent(false)
  }
  //获取验证码倒计时
  useEffect(() => {
    if (!isSendEmail) return
    let timer = null;
    clearTimeout(timer)
    timer = setTimeout(() => {
      if (count > 1) {
        setCount(count - 1)
      } else {
        setIsSendEmail(false)
      }
    }, 1000)
    return () => clearInterval(timer);
  }, [count, isSendEmail])
  //切换表单类型
  useEffect(() => {
    setIsSendEmail(false)
    form.resetFields(); // 重置表单
  }, [formType])
  //发送验证码
  const onSendCode = async (e) => {
    let value = emailRef.current.input.value;
    if (!(/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value))) {
      messageApi.open({
        type: 'warning',
        content: `${t('请输入正确的邮箱')}`,
        duration: 3,
      });
      return
    }
    const res = await axios({
      url: BASE_URL + 'front/sendInviteCode',
      method: 'get',   // 默认值
      params: {    // params 会与 URL 拼接。
        username: value
      }
    })
    if (res.data.code === 200) {
      messageApi.open({
        type: 'success',
        content: `${t('发送成功')}`,
        duration: 3,
      });
      setIsSendEmail(true)
      setCount(60)
    } else {
      messageApi.open({
        type: 'warning',
        content: res.data.msg,
        duration: 3,
      });
    }

  }
  return (
    <>
      {contextHolder}
      <Modal open={show} onCancel={close} footer={null} maskClosable={false}>
        <div className='text-2xl font-bold text-center my-5'>{formType === 'login' ? `${t('登录')}` : formType === 'register' ? `${t('注册')}` : `${t('找回密码')}`}</div>
        {/* 登录 */}
        {formType === 'login' && <Form layout="vertical" form={form} onFinish={loginSubmit} size={'large'}>
          <Form.Item label={t('邮箱')} name="username" rules={[{ required: true, message: `${t('请输入邮箱账号')}` }]} >
            <Input type='email' value={loginFormData.username} />
          </Form.Item>
          <Form.Item label={t('密码')} name="password" rules={[{ required: true, message: `${t('请输入密码')}` }]} >
            <Input value={loginFormData.password} maxLength={16} />
          </Form.Item>
          <Form.Item>
            <div className='flex justify-between items-center'>
              <Button className='bg-[#728D6B] text-white' htmlType="submit">
                {t('登录')}
              </Button>
              <div className=' cursor-pointer text-[#728D6B]'>
                <span onClick={() => setFormType('findPassword')} className='mr-2 hover:underline'>{t('忘记密码？')}</span>
                <span onClick={() => setFormType('register')} className='hover:underline'>{t('注册')}</span>
              </div>
            </div>
          </Form.Item>
        </Form>}
        {/* 注册 */}
        {formType === 'register' && <Form layout="vertical" form={form} onFinish={registerSubmit} size={'large'}>
          <Form.Item label={t('昵称')} name="nickName" rules={[
            { required: true, message: `${t('请输入昵称')}` }]} >
            <Input value={registerFormData.nickName} maxLength={8} />
          </Form.Item>
          <div className='relative' >
            <Form.Item label={t('邮箱')} name="username" rules={[{ required: false, message: `${t('请输入邮箱账号')}` }]}>
              <Input type='email' value={registerFormData.username} ref={emailRef} />
            </Form.Item>
            <div
              onClick={() => onSendCode('registerFormData')}
              className={classNames('absolute top-[71%] right-4 translate-y-[-50%] cursor-pointer', isSendEmail && 'text-[#999]')}
            >
              {isSendEmail ? `${count}${t('秒后重新获取')}` : `${t('获取验证码')}`}
            </div>
          </div>
          <Form.Item label={t('验证码')} name="code" rules={[{ required: true, message: `${t('请输入验证码')}` }]} >
            <Input value={registerFormData.code} />
          </Form.Item>
          <Form.Item label={t('密码')} name="password" rules={[{ required: true, message: `${t('请输入密码')}` }]} >
            <Input value={registerFormData.password} maxLength={16} />
          </Form.Item>
          <Form.Item label={t('确认密码')} name="confirm" dependencies={['password']}
            hasFeedback rules={[{ required: true, message: `${t('请输入确认密码')}` }, ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error(`${t('两次密码不一致')}`));
              },
            }),]} >
            <Input value={registerFormData.surePassword} />
          </Form.Item>
          <Form.Item label={t('邀请码')} name="inviteCode" rules={[{ required: true, message: `${t('请输入邀请码')}` }]}>
            <Input value={registerFormData.inviteCode} />
          </Form.Item>
          <Form.Item>
            <div className='flex justify-between items-center'>
              <Button className='bg-[#728D6B] text-white' htmlType="submit">
                {t('注册')}
              </Button>
              <div className='cursor-pointer text-[#728D6B]'>
                <span onClick={() => setFormType('findPassword')} className='mr-2 hover:underline'>{t('忘记密码？')}</span>
                <span onClick={() => setFormType('login')} className='hover:underline'>{t('登录')}</span>
              </div>
            </div>
          </Form.Item>
        </Form>}
        {/* 找回密码 */}
        {formType === 'findPassword' && <Form layout="vertical" form={form} onFinish={forgetSubmit} size={'large'}>
          <div className='relative' >
            <Form.Item label={t('邮箱')} name="username">
              <Input value={findFormData.username} ref={emailRef} />
            </Form.Item>
            <div
              onClick={() => onSendCode('findFormData')}
              className={classNames('absolute top-[71%] right-4 translate-y-[-50%] cursor-pointer', isSendEmail && 'text-[#999]')}
            >
              {isSendEmail ? `${count}${t('秒后重新获取')}` : `${t('获取验证码')}`}
            </div>
          </div>
          <Form.Item label={t('验证码')} name="code" rules={[{ required: true, message: `${t('请输入验证码')}` }]} >
            <Input value={findFormData.code} />
          </Form.Item>
          <Form.Item label={t('新密码')} name="password" rules={[{ required: true, message: `${t('请输入新密码')}` }]} >
            <Input value={findFormData.password} />
          </Form.Item>
          <Form.Item label={t('确认密码')} name="passwordConfirm" rules={[{ required: true, message: `${t('请输入确认新密码')}` }]} >
            <Input value={findFormData.passwordConfirm} />
          </Form.Item>
          <Form.Item>
            <div className='flex justify-between items-center'>
              <Button className='bg-[#728D6B] text-white' htmlType="submit">
                {t('确认')}
              </Button>
              <div className=' cursor-pointer text-[#728D6B] '>
                <span onClick={() => setFormType('register')} className='mr-2 hover:underline'>{t('注册')}</span>
                <span onClick={() => setFormType('login')} className='hover:underline'>{t('登录')}</span>
              </div>
            </div>
          </Form.Item>
        </Form>}
      </Modal>
    </>
  )
}

export default Login